package com.xindaoapp.happypet.ui;

import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.bean.AddressInfo;
import com.xindaoapp.happypet.bean.BaseEntity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 收货人信息列表
 * 
 * @author chenghao
 * 
 */
public class ConsigneeActivity extends BaseActivity {
    private ListView mListView;
    private List<AddressInfo> addressList;

    @Override
    protected int getContentViewResId() {
        return R.layout.layout_consignee;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setTopBarTitle("收货人信息");
        mListView = (ListView) findViewById(R.id.listview);
    }

    @Override
    protected void initEvents() {
        super.initEvents();

    }

    /**
     * 删除地址
     */
    private void deleteAddress(final String addressID) {

        getMoccaApi().getDeleteAddressInfo(String.valueOf(UserState.getUserUid()), addressID,
                new IRequest<BaseEntity>() {

                    @Override
                    public void request(BaseEntity t) {
                        if ("1".equals(t.getStatus())) {
                            Toast.makeText(getBaseContext(), "地址删除成功！", Toast.LENGTH_SHORT).show();
                            for (AddressInfo adress : addressList) {
                                if (addressID.equals(adress.address_id)) {
                                    addressList.remove(adress);
                                    ((ConsigneeAdapter) mListView.getAdapter())
                                            .resetList(addressList);
                                    ((ConsigneeAdapter) mListView.getAdapter())
                                            .notifyDataSetChanged();
                                    if (addressList.size() == 0) {
                                        onDataArrivedEmpty();
                                    }
                                    break;
                                }
                            }
                        }

                    }
                });
    }

    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();
        getMoccaApi().getMyAddress(UserState.getUserUid(), new IRequest<List<AddressInfo>>() {


            @Override
            public void request(List<AddressInfo> t) {
                if (null != t) {
                    onDataArrived(true);
                    if (t.size() == 0) {
                        onDataArrivedEmpty();
                    } else {
                        addressList = t;
                        if (null == mListView.getAdapter()) {
                            mListView.setAdapter(new ConsigneeAdapter(t));
                        } else {
                            ((ConsigneeAdapter) mListView.getAdapter()).resetList(t);
                            ((ConsigneeAdapter) mListView.getAdapter()).notifyDataSetChanged();
                        }
                    }
                } else {
                    onDataArrived(false);
                }
            }
        });
    }

    class ConsigneeAdapter extends BaseAdapter {
        private List<AddressInfo> list;

        public ConsigneeAdapter(List<AddressInfo> list) {
            super();
            this.list = list;
        }

        public void resetList(List<AddressInfo> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView =
                        LayoutInflater.from(ConsigneeActivity.this).inflate(
                                R.layout.item_consignee, null);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.phoneNumber = (TextView) convertView.findViewById(R.id.phone_number);
                holder.address = (TextView) convertView.findViewById(R.id.address);
                holder.checkBox = (ImageView) convertView.findViewById(R.id.check_box);
                holder.edit = convertView.findViewById(R.id.edit);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final AddressInfo info = list.get(position);
            holder.name.setText(info.username);
            holder.phoneNumber.setText(info.mobile);
            holder.address.setText(info.address);
            int isdefault = 0;
            try {
                isdefault = Integer.parseInt(info.isdefault);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (isdefault == 1) {
                holder.checkBox.setSelected(true);
                // holder.checkBox.setImageResource(R.drawable.check_selected);
            } else {
                holder.checkBox.setSelected(false);
                // holder.checkBox.setImageResource(R.drawable.check_all_normal);
            }
            holder.edit.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // startFragment(new NewConsigneeFragment(), bundle);
                    Intent intent = new Intent(ConsigneeActivity.this, NewConsigneeActivity.class);
                    // Bundle bundle = new Bundle();
                    // bundle.putSerializable(Constants.KEY_CONSIGNEE, info);
                    intent.putExtra(Constants.KEY_CONSIGNEE, info);
                    startActivity(intent);
                }
            });

            holder.checkBox.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // 设置为默认
                    getMoccaApi().setDefaultAddressDetail(UserState.getUserUid(), info.address_id,
                            new IRequest<Boolean>() {

                                @Override
                                public void request(Boolean t) {
                                    if (ConsigneeActivity.this == null) {
                                        return;
                                    }
                                    if (t) {
                                        Toast.makeText(ConsigneeActivity.this, "设置默认地址成功！",
                                                Toast.LENGTH_SHORT).show();
                                        // 刷新填写订单页面
                                        // Bundle bundle = new Bundle();
                                        // bundle.putSerializable(Constants.KEY_CONSIGNEE, info);
                                        // setBundle(bundle);
                                        onLoadDatas();

                                        // backFragment();

                                    } else {
                                        Toast.makeText(ConsigneeActivity.this, "设置默认地址失败！",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                }
            });
            convertView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // if (getArguments() == null
                    // || getArguments().getBoolean(Constants.KEY_IS_BACK, true)) {
                    // // 返回上一个界面。并传值给前一个界面
                    // Bundle bundle = new Bundle();
                    // bundle.putSerializable(Constants.KEY_CONSIGNEE, info);
                    // setBundle(bundle);
                    // backFragment();
                    // }

                    // 设置为默认
                    getMoccaApi().setDefaultAddressDetail(UserState.getUserUid(), info.address_id,
                            new IRequest<Boolean>() {

                                @Override
                                public void request(Boolean t) {
                                    if (ConsigneeActivity.this == null) {
                                        return;
                                    }
                                    if (t) {
                                        Toast.makeText(ConsigneeActivity.this, "设置默认地址成功！",
                                                Toast.LENGTH_SHORT).show();
                                        // 刷新填写订单页面
                                        // Bundle bundle = new Bundle();
                                        // bundle.putSerializable(Constants.KEY_CONSIGNEE, info);
                                        // setBundle(bundle);
                                        onLoadDatas();

                                        // backFragment();
                                    } else {
                                        Toast.makeText(ConsigneeActivity.this, "设置默认地址失败！",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                }
            });

            convertView.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {

                    new AlertDialog.Builder(ConsigneeActivity.this)
                            .setMessage("确认删除地址？")
                            .setNegativeButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    deleteAddress(info.address_id);
                                }
                            })
                            .setPositiveButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {}
                                    }).show().setCancelable(true);

                    return false;
                }
            });

            return convertView;
        }

        class ViewHolder {
            TextView name;
            TextView phoneNumber;
            TextView address;
            ImageView checkBox;
            View edit;
        }

    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        };
    }

    @Override
    protected int getTopBarRightTextViewRes() {
        return R.string.add_address;
    }

    @Override
    protected OnClickListener getRightViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ConsigneeActivity.this, NewConsigneeActivity.class);
                startActivity(intent);
            }
        };
    }

    @Override
    public void onResume() {
        super.onResume();
        onLoadDatas();
    }
}
